<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:class_add>新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :showPagination="false"
      >
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleChangeStatus(record)" v-action:class_status_update>{{ record.status == 0 ? '启用' : '禁用' }}</a>
            <a-divider type="vertical" v-action:class_edit/>
            <a @click="handleEdit(record)" v-action:class_edit>编辑</a>
            <a-divider type="vertical" v-action:class_status_update/>
            <a @click="handleRemove(record)" v-action:class_status_update>删除</a>
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
        :okHidden="okHidden"
      />
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import CreateForm from './modules/CreateContentForm'
import { sortList, addSort, changeStatus, editSort } from '@/api/exam'
const filterStatus = {
  0: '禁用',
  1: '启用'
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    align: 'center'
  },
  {
    title: '分类名称  ',
    dataIndex: 'class_name',
    align: 'center'
  },
  {
    title: '绑定问卷',
    dataIndex: 'surveys_count',
    align: 'center',
    scopedSlots: { customRender: 'surveys_count' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    customRender: i => filterStatus[i]
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    STable,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false,
      mdl: { class_name: null },
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        const res = await sortList(parameter)
        const result = {
          pageNo: 1,
          totalPage: 1,
          data: res.list,
          pageSize: res.list.length,
          totalCount: res.list.length
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  created () {
    sortList().then(res => {
      console.log(res.list)
      this.sortList = res.list
    }).catch(err => {
      console.log('错误', err)
    })
  },
  methods: {
    handleAdd () {
      this.mdl = { class_name: null }
      this.visible = true
    },
    handleEdit (record) {
      // console.log(record)
      this.visible = true
      this.mdl = { ...record }
      // console.log()
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const success = (res, info) => {
            if (res.is_ok === 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          if (values.id > 0) {
            console.log(values)
            editSort(values)
              .then(res => success(res, '修改成功'))
              .finally(final)
          } else {
            addSort(values)
              .then(res => success(res, '新增成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeStatus (record) {
      this.openModal(changeStatus, record, record.status === 0 ? '启用' : '禁用')
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该分类吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            if (statusText == '启用') {
              const res = await method({ id: record.id, status: !record.status })
              if (res.is_ok === 'Y') {
                this.modal.loading = false
                this.modal.show = false
                this.$refs.table.refresh()
                this.$message.info(`${ statusText }成功`)
              }
            } else if (statusText == '禁用') {
              const res = await method({ id: record.id, status: !record.status })
              if (res.is_ok === 'Y') {
                this.modal.loading = false
                this.modal.show = false
                this.$refs.table.refresh()
                this.$message.info(`${ statusText }成功`)
              }
            } else {
              const res = await method({ id: record.id, status: 3 })
              if (res.is_ok === 'Y') {
                this.modal.loading = false
                this.modal.show = false
                this.$refs.table.refresh()
                this.$message.info(`${ statusText }成功`)
              }
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.handleVisible()
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    async handleRemove (record) {
      this.openModal(changeStatus, record, '删除')
    },
    handleVisible () {
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {}
    }
  }
}
</script>
